package com.example.hospitalapp;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class AppointmentActivity extends AppCompatActivity {

    private Spinner spinnerSpecialty, spinnerDoctor;
    private Button btnBookAppointment;
    private EditText edtAppointmentTime;
    private Patient patient;
    private String selectedAppointmentTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appointment);

        // 获取患者信息
        patient = (Patient) getIntent().getSerializableExtra("patient_info");

        spinnerSpecialty = findViewById(R.id.spinnerSpecialty);
        spinnerDoctor = findViewById(R.id.spinnerDoctor);
        edtAppointmentTime = findViewById(R.id.edtAppointmentTime);
        btnBookAppointment = findViewById(R.id.btnBookAppointment);

        // 加载科室列表
        loadSpecialties();

        // 科室选择变化时加载医生列表
        spinnerSpecialty.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // 获取选择的科室名称
                String specialtyName = spinnerSpecialty.getSelectedItem().toString();
                // 加载对应科室的医生
                loadDoctorsBySpecialty(specialtyName);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
            }
        });


        // 点击预约时间框，弹出时间选择器
        edtAppointmentTime.setOnClickListener(v -> {
            showDateTimePicker();
        });

        // 点击预约按钮，提交预约请求
        btnBookAppointment.setOnClickListener(view -> {
            String doctorName = spinnerDoctor.getSelectedItem().toString();
            if (selectedAppointmentTime != null) {
                createAppointment(patient.getPatientId(), doctorName, selectedAppointmentTime);
            } else {
                Toast.makeText(AppointmentActivity.this, "请选择预约时间", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 加载科室列表
    private void loadSpecialties() {
        ApiClient apiClient = new ApiClient(AppointmentActivity.this);
        apiClient.getRequest("http://zhsj.autumnclouds.cn/specialties", new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    JSONArray specialties = response.getJSONArray("data");
                    List<String> specialtyList = new ArrayList<>();
                    for (int i = 0; i < specialties.length(); i++) {
                        String specialty = specialties.getString(i);  // 获取科室名称
                        specialtyList.add(specialty);
                    }

                    // 填充科室选择器
                    ArrayAdapter<String> specialtyAdapter = new ArrayAdapter<>(AppointmentActivity.this, android.R.layout.simple_spinner_item, specialtyList);
                    spinnerSpecialty.setAdapter(specialtyAdapter);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }

    // 根据科室名称加载医生列表
    private void loadDoctorsBySpecialty(String specialtyName) {
        ApiClient apiClient = new ApiClient(AppointmentActivity.this);

        // 使用科室名称而不是ID查询医生
        apiClient.getRequest("http://zhsj.autumnclouds.cn/doctor/of/specialty/" + specialtyName, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    JSONArray doctors = response.getJSONArray("data");
                    List<String> doctorList = new ArrayList<>();
                    for (int i = 0; i < doctors.length(); i++) {
                        JSONObject doctor = doctors.getJSONObject(i);
                        doctorList.add(doctor.getString("name")); // 获取医生名称
                    }

                    // 填充医生选择器
                    ArrayAdapter<String> doctorAdapter = new ArrayAdapter<>(AppointmentActivity.this, android.R.layout.simple_spinner_item, doctorList);
                    spinnerDoctor.setAdapter(doctorAdapter);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }

    // 显示日期和时间选择器
    private void showDateTimePicker() {
        final Calendar calendar = Calendar.getInstance();

        // 日期选择器
        DatePickerDialog datePickerDialog = new DatePickerDialog(AppointmentActivity.this,
                (view, year, monthOfYear, dayOfMonth) -> {
                    // 时间选择器
                    TimePickerDialog timePickerDialog = new TimePickerDialog(AppointmentActivity.this,
                            (view1, hourOfDay, minute) -> {
                                // 格式化选择的时间
                                selectedAppointmentTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " " +
                                        hourOfDay + ":" + minute;
                                edtAppointmentTime.setText(selectedAppointmentTime);  // 设置到编辑框
                            },
                            calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
                    timePickerDialog.show();
                },
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    // 创建预约
    private void createAppointment(int patientId, String doctorName, String appointmentTime) {
        JSONObject params = new JSONObject();
        try {
            // 根据医生姓名获取医生ID
            getDoctorIdByName(doctorName, doctorId -> {
                try {
                    params.put("patientId", patientId);
                    params.put("doctorId", doctorId); // 获取医生ID
                    params.put("appointmentTime", formatAppointmentTime(appointmentTime));  // 格式化时间
                    params.put("status", "未就诊");  // 预约状态
                    params.put("paymentStatus", "未付款");  // 支付状态

                    ApiClient apiClient = new ApiClient(AppointmentActivity.this);
                    apiClient.postRequest("http://zhsj.autumnclouds.cn/appointment", params, new ApiClient.VolleyCallback() {
                        @Override
                        public void onSuccess(JSONObject response) {
                            Toast.makeText(AppointmentActivity.this, "预约成功！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(String error) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 格式化时间为 yyyy-MM-dd HH:mm:ss 格式
    private String formatAppointmentTime(String appointmentTime) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = inputFormat.parse(appointmentTime);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return outputFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return appointmentTime;  // 如果格式化失败，返回原始时间
        }
    }

    // 获取医生ID（通过医生姓名查询）
    private void getDoctorIdByName(String doctorName, DoctorIdCallback callback) {
        ApiClient apiClient = new ApiClient(AppointmentActivity.this);
        JSONObject params = new JSONObject();
        try {
            params.put("name", doctorName); // 将医生姓名传递给接口
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 调用接口查询医生信息
        apiClient.postRequest("http://zhsj.autumnclouds.cn/doctor/query", params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        JSONArray data = response.getJSONArray("data");
                        if (data.length() > 0) {
                            JSONObject doctorInfo = data.getJSONObject(0);
                            int doctorId = doctorInfo.getInt("doctorId");
                            // 返回医生ID
                            callback.onDoctorIdFetched(doctorId);
                        } else {
                            Toast.makeText(AppointmentActivity.this, "未找到该医生", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        String msg = response.getString("msg");
                        Toast.makeText(AppointmentActivity.this, "错误: " + msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(AppointmentActivity.this, "查询医生信息失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }

    // 医生ID回调接口
    interface DoctorIdCallback {
        void onDoctorIdFetched(int doctorId);
    }
}
